﻿var titBook = titBook || {};
titBook.module = titBook.module || {};

titBook.core.register("leftMenu-module", function (sandbox) {
    return {
        activate: function () {
            var itemsViewModel = new titBook.viewModels.LeftMenuViewModel(this.updateItems);
        },

        destroy: function () {
            sandbox.removeAllListeners();
        },

        selectedItem: undefined,

        updateItems: function (items) {

            var me = this,
                dataSource = new kendo.data.DataSource({
                    data: items
                }),
                listView,
                itemToSelect;

            $("#leftListView").kendoListView({
                dataSource: dataSource,
                selectable: "single",
                change: onSelectedChange,
                template: "<div id='#:Url#'><p>#:Title#</p></div>"
            });

            listView = $("#leftListView").data("kendoListView"),
            itemToSelect = listView.element.children().first();

            listView.select(itemToSelect);
            me.selectedItem = itemToSelect.attr("id");
            
            function onSelectedChange() {
                var selected = $("#leftListView > .k-state-selected").attr("id");

                if (me.selectedItem !== selected) {
                    router.navigate("/" + selected);
                    sandbox.notify("leftMenuItemChanged", selected);
                    me.selectedItem = selected;
                }
            }
        }
    };
});